package cn.edu.scau.cmi.wuzhenxin.hibernate.service;

import java.util.List;
import java.util.Set;

import cn.edu.scau.cmi.wuzhenxin.hibernate.dao.StudentDAOByHibernate;
import cn.edu.scau.cmi.wuzhenxin.hibernate.dao.TeacherDAOByHibernate;
import cn.edu.scau.cmi.wuzhenxin.hibernate.domain.Student;
import cn.edu.scau.cmi.wuzhenxin.hibernate.domain.Teacher;

public class TeacherService {
	
	private TeacherDAOByHibernate teacherDAOByHibernate = new TeacherDAOByHibernate();
	
	public Teacher findById(Integer id) {
		return teacherDAOByHibernate.findById(id);
	}

	public List<Teacher> findAll(){
		return teacherDAOByHibernate.findAll();
	}
	
	public boolean saveTeacher(String name) {
		Teacher teacher = new Teacher();
		teacher.setName(name);
		return teacherDAOByHibernate.save(teacher);
	}
	
	public boolean deleteTeacher(Integer id) {
		Teacher teacher = teacherDAOByHibernate.findById(id);
		//先对学生进行处理
		Set<Student> students = teacher.getStudents();
		StudentService studentService = new StudentService();
		Teacher tutor = teacherDAOByHibernate.findById(1);
		for (Student student : students) {
			studentService.modifyStudent(student.getId(), "", tutor);
		}
		return teacherDAOByHibernate.deleteById(teacher);
	}
	
	public boolean modifyTeacher(int id, String name) {
		Teacher teacher = teacherDAOByHibernate.findById(id);
		if(teacher == null) {
			return false;
		}
		if(name.length()>0) {
			teacher.setName(name);
		}
		return teacherDAOByHibernate.updateById(teacher);
	}

}
